package com.efounder.news.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import androidx.recyclerview.widget.RecyclerView;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.language.MultiLanguageUtil;
import com.efounder.mobilenews.R;
import com.efounder.news.bean.CommentListBean;
import com.efounder.news.http.Api;
import com.efounder.news.irecyclerview.IViewHolder;
import com.efounder.util.AppContext;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.Utils;

import java.util.ArrayList;
import java.util.List;

import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;

/**
 * 新闻详情页的Adapter
 * Created by slp on 2017/12/3.
 */

public class CommentAdapter extends RecyclerView.Adapter {

    private final String TAG = CommentAdapter.class.getSimpleName();

    private static final int WEB_VIEW =5;//新闻网页
    private static final int NORMAL_COMMENT = 0;//普通评论
    private static final int ONE_REPLY = 1;//一条回复的评论
    private static final int TWO_REPLY = 2;//两条回复
    private static final int THREE_REPLY = 3;//三条回复

    //点击item
    private OnItemClickListener mOnItemClickListener;
    //点赞
    private OnGoodClickListener mOnGoodClickListener;
    //取消赞
    private OnBadClickListener mOnBadClickListener;

    private OnWebViewListener mOnWebViewListener;

    private Context mContext;

    private List<CommentListBean> mCommentList;

    private String webUrl;

    /**
     * 是否支持积分显示
     */
    private boolean isSupportNewsCommentIntegral;

    public CommentAdapter(Context context, List<CommentListBean> list, String url){
        mContext = context;
        mCommentList = list;
        webUrl = url;
        isSupportNewsCommentIntegral = EnvSupportManager.isSupportShowIntergral();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view;

        if (viewType == NORMAL_COMMENT){
            view = LayoutInflater.from(mContext).inflate(R.layout.item_comment,parent, false);
            return new NoViewHolder(view);
        }else if(viewType == ONE_REPLY){
            view = LayoutInflater.from(mContext).inflate(R.layout.item_comment_1reply,parent, false);
            return new OneViewHolder(view);
        }else if(viewType == TWO_REPLY){
            view = LayoutInflater.from(mContext).inflate(R.layout.item_comment_2reply,parent, false);
            return new TwoViewHolder(view);
        }else if(viewType == THREE_REPLY){
            view = LayoutInflater.from(mContext).inflate(R.layout.item_comment_3reply,parent, false);
            return new ThreeViewHolder(view);
        }
        else{
            view = LayoutInflater.from(mContext).inflate(R.layout.item_webview,parent, false);
            return new WebViewHolder(view, webUrl);
        }

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
//        if(holder instanceof WebViewHolder){
//            WebViewHolder webViewHolder = (WebViewHolder)holder;
//        }
            holder.itemView.setVisibility(View.VISIBLE);
            if(holder instanceof ViewHolder){
                CommentListBean commentListBean = mCommentList.get(position - 1);
                final ViewHolder viewHolder = (ViewHolder)holder;

                if (getItemViewType(position) == ONE_REPLY){
                    OneViewHolder oneViewHolder = (OneViewHolder) viewHolder;

                    oneViewHolder.itemView.setVisibility(View.VISIBLE);

                    ArrayList<CommentListBean.replyComment> replyList = commentListBean.getReplyList();
                    CommentListBean.replyComment replyComment = replyList.get(0);

                    SpannableStringBuilder userNameBuilder = new SpannableStringBuilder(replyComment.getUserName());
                    ForegroundColorSpan nameColor = new ForegroundColorSpan(Color.parseColor("#406599"));
                    userNameBuilder.setSpan(nameColor, 0, userNameBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

                    SpannableString replyText = new SpannableString(":" + replyComment.getText());
//                    ForegroundColorSpan textColor = new ForegroundColorSpan(Color.parseColor("#505050"));
                    ForegroundColorSpan textColor = new ForegroundColorSpan(mContext.getResources().getColor(R.color.black_text_color));
                    replyText.setSpan(textColor, 0, replyText.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

                    userNameBuilder.append(replyText);
                    oneViewHolder.reply1.setText(userNameBuilder);

                    oneViewHolder.rePlyCount.setText(mContext.getString(R.string.detail_see_all_comment,commentListBean.getReplyCount()));
                    oneViewHolder.rePlyCount.setVisibility(View.GONE);

                }else if(getItemViewType(position) == TWO_REPLY){
                    TwoViewHolder twoViewHolder = (TwoViewHolder) viewHolder;

                    twoViewHolder.itemView.setVisibility(View.VISIBLE);

                    ArrayList<CommentListBean.replyComment> replyList = commentListBean.getReplyList();

                    CommentListBean.replyComment replyComment0 = replyList.get(0);
                    CommentListBean.replyComment replyComment1 = replyList.get(1);

                    SpannableStringBuilder userNameBuilder0 = new SpannableStringBuilder(replyComment0.getUserName());
                    ForegroundColorSpan nameColor = new ForegroundColorSpan(Color.parseColor("#406599"));
                    userNameBuilder0.setSpan(nameColor, 0, userNameBuilder0.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

                    SpannableString replyText0 = new SpannableString(":" + replyComment0.getText());
                    ForegroundColorSpan textColor = new ForegroundColorSpan(mContext.getResources().getColor(R.color.black_text_color));
                    replyText0.setSpan(textColor, 0, replyText0.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

                    userNameBuilder0.append(replyText0);

                    SpannableStringBuilder userNameBuilder1 = new SpannableStringBuilder(replyComment1.getUserName());
                    userNameBuilder1.setSpan(nameColor, 0, userNameBuilder1.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

                    SpannableString replyText1 = new SpannableString(":" + replyComment1.getText());
                    replyText1.setSpan(textColor, 0, replyText1.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

                    userNameBuilder1.append(replyText1);

                    twoViewHolder.reply1.setText(userNameBuilder0);
                    twoViewHolder.reply2.setText(userNameBuilder1);

                    twoViewHolder.rePlyCount.setText(mContext.getString(R.string.detail_see_all_comment,commentListBean.getReplyCount()));
                    twoViewHolder.rePlyCount.setVisibility(View.GONE);

                }else if(getItemViewType(position) == THREE_REPLY){
                    ThreeViewHolder threeViewHolder = (ThreeViewHolder) viewHolder;

                    threeViewHolder.itemView.setVisibility(View.VISIBLE);

                    ArrayList<CommentListBean.replyComment> replyList = commentListBean.getReplyList();

                    CommentListBean.replyComment replyComment0 = replyList.get(0);
                    CommentListBean.replyComment replyComment1 = replyList.get(1);
                    CommentListBean.replyComment replyComment2 = replyList.get(2);

                    SpannableStringBuilder userNameBuilder0 = new SpannableStringBuilder(replyComment0.getUserName());
                    ForegroundColorSpan nameColor = new ForegroundColorSpan(Color.parseColor("#406599"));
                    userNameBuilder0.setSpan(nameColor, 0, userNameBuilder0.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

                    SpannableString replyText0 = new SpannableString(":" + replyComment0.getText());
//                    ForegroundColorSpan textColor = new ForegroundColorSpan(Color.parseColor("#505050"));
                    ForegroundColorSpan textColor = new ForegroundColorSpan(mContext.getResources().getColor(R.color.black_text_color));

                    replyText0.setSpan(textColor, 0, replyText0.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

                    userNameBuilder0.append(replyText0);

                    SpannableStringBuilder userNameBuilder1 = new SpannableStringBuilder(replyComment1.getUserName());
                    userNameBuilder1.setSpan(nameColor, 0, userNameBuilder1.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

                    SpannableString replyText1 = new SpannableString(":" + replyComment1.getText());
                    replyText1.setSpan(textColor, 0, replyText1.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

                    userNameBuilder1.append(replyText1);

                    SpannableStringBuilder userNameBuilder2 = new SpannableStringBuilder(replyComment2.getUserName());
                    userNameBuilder2.setSpan(nameColor, 0, userNameBuilder2.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

                    SpannableString replyText2 = new SpannableString(":" + replyComment2.getText());
                    replyText2.setSpan(textColor, 0, replyText2.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

                    userNameBuilder2.append(replyText2);

                    threeViewHolder.reply1.setText(userNameBuilder0);
                    threeViewHolder.reply2.setText(userNameBuilder1);
                    threeViewHolder.reply3.setText(userNameBuilder2);
                    int replyCount = Integer.parseInt(commentListBean.getReplyCount());
                    if(replyCount > 3){
                        threeViewHolder.rePlyCount.setText(mContext.getString(R.string.detail_see_all_comment,commentListBean.getReplyCount()));
                    }else {
                        threeViewHolder.rePlyCount.setVisibility(View.GONE);
                    }
                }
                //是否显示积分
                isSupportNewsCommentIntegral(viewHolder);
                viewHolder.tvNewsCommentIntegral.setText(mContext.getString(R.string.news_comment_add_silver_drill,commentListBean.getIntegral()));
                viewHolder.text.setText(commentListBean.getComment());
                viewHolder.createTime.setText(commentListBean.getCommentDate());
                viewHolder.userName.setText(commentListBean.getUserName());

                if (commentListBean.getReplyCount().equals("0")) {
                    viewHolder.replyNum.setText(ResStringUtil.getString(R.string.detail_reply));
                } else {
                    viewHolder.replyNum.setText(commentListBean.getReplyCount() + ResStringUtil.getString(R.string.detail_reply));
                }

                if (commentListBean.getDiggCount().equals("0")) {
                    viewHolder.favourCount.setText(R.string.detail_zan);
                } else {
                    viewHolder.favourCount.setText(commentListBean.getDiggCount());
                }
                String userDigg = commentListBean.getUserDigg();
                if (userDigg.equals("1")) {
                    viewHolder.likeImg.setImageResource(R.drawable.good_checked);
                } else {
                    viewHolder.likeImg.setImageResource(R.drawable.good);
                }

                viewHolder.itemView.setOnClickListener(new View.OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        int pos = viewHolder.getIAdapterPosition();
                        if(mOnItemClickListener != null){
                            mOnItemClickListener.onItemClick(viewHolder.itemView, pos );
                        }
                    }
                });
                viewHolder.likeImg.setEnabled(true);
                viewHolder.likeImg.setOnClickListener(new View.OnClickListener() {
                    CommentListBean mCommentListBean = mCommentList.get(position - 1);
                    String userDigg = mCommentListBean.getUserDigg();
                    String diggCount = mCommentListBean.getDiggCount();


                    @Override
                    public void onClick(View v) {
                        //防止多次点击
                        viewHolder.likeImg.setEnabled(false);
                        if (userDigg.equals("0")) {
//                            int dCount = Integer.parseInt(diggCount);
//                            dCount += 1;
//                            diggCount = String.valueOf(dCount);
//                            mCommentListBean.setUserDigg("1");
//                            mCommentListBean.setDiggCount(diggCount);
                            if (mOnGoodClickListener != null) {
                                mOnGoodClickListener.onGoodClick( position );
                            }
                        } else {
//                            mCommentListBean.setUserDigg("0");
//                            int dCount = Integer.parseInt(diggCount);
//                            dCount -= 1;
//                            diggCount = String.valueOf(dCount);
//                            mCommentListBean.setDiggCount(diggCount);

                            if (mOnBadClickListener != null) {
                                mOnBadClickListener.onBadClick( position );
                            }
                        }
                    }
                });

                setNetPicture(Api.getAvator + commentListBean.getUserId(), viewHolder.userImg);

            }

    }

    @Override
    public int getItemViewType(int position) {
        int viewType = NORMAL_COMMENT;
        if(position == 0){
            return WEB_VIEW;
        }
        CommentListBean commentListBean = mCommentList.get(position -1);
        ArrayList<CommentListBean.replyComment> replyList = commentListBean.getReplyList();
        if (replyList.size() > 2){
            viewType = THREE_REPLY;
        }else if(replyList.size() == 2){
            viewType = TWO_REPLY;
        }else if (replyList.size() == 1){
            viewType = ONE_REPLY;
        }

        return viewType;
    }

    @Override
    public int getItemCount() {
        return mCommentList.size() + 1;
    }

    /**
     * 判断是否显示积分
     * @param viewHolder 当前item的viewHolder
     */
    private void isSupportNewsCommentIntegral(ViewHolder viewHolder){
        if(isSupportNewsCommentIntegral){
            viewHolder.ivNewsCommentIconIntegral.setVisibility(View.VISIBLE);
            viewHolder.tvNewsCommentIntegral.setVisibility(View.VISIBLE);
        }else {
            viewHolder.ivNewsCommentIconIntegral.setVisibility(View.GONE);
            viewHolder.tvNewsCommentIntegral.setVisibility(View.GONE);
        }

    }

    public void addItems(List<CommentListBean> lists){
        mCommentList.addAll(lists);
        notifyItemRangeInserted(1, lists.size());
    }
    public void addAll(List<CommentListBean> list){
        mCommentList.addAll(list);
        notifyDataSetChanged();
    }
    public void refresh(List<CommentListBean> list){
        mCommentList.removeAll(mCommentList);
        mCommentList.addAll(list);
        notifyDataSetChanged();
    }
    /**
     * 获取头像
     *
     * @param url
     * @param img
     */
    private void setNetPicture(String url, ImageView img) {
        Glide
                .with(mContext)
                .load(url)
                .transition(new DrawableTransitionOptions().crossFade())
                .apply(new RequestOptions().placeholder(R.mipmap.default_userhead)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .transform(new CircleCrop()))
                .into(img);
    }

    /**
     * webview的viewHolder
     */
    public class WebViewHolder extends IViewHolder {
        public WebView mWebView;
//        public String url = "http://211.87.224.140:8181/NewsService/news/b6046981a84c9b9d2ec3bf844d986a342f697cbf7fcca833c28cbbf1d508bd1a";

        private WebViewHolder(View itemView, String url){
            super(itemView);
            //todo 修复使用Application加载字符串 多语言切换失效问题
            MultiLanguageUtil.setApplicationLanguage(Utils.getApp());
            LoadingDataUtilBlack.show(itemView.getContext(), ResStringUtil.getString(R.string.common_text_loading));
            mWebView = (WebView) itemView.findViewById(R.id.news_web_view);
            mWebView.setBackgroundColor(mContext.getResources().getColor(R.color.frame_white_background_color));

            WebSettings settings = mWebView.getSettings();
            mWebView.getSettings().setJavaScriptEnabled(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
            } else {
                settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
            }

            mWebView.setWebViewClient(new WebViewClient(){
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);

                    if (EnvironmentVariable.getProperty(KEY_SETTING_APPID, "").equals(AppContext.getInstance()
                            .getString(R.string.special_appid)) &&
                            !EnvSupportManager.isSupportGooglePlayUpgrade()) {
                        //这段js 是为了改变网页文字颜色。。。参考 https://blog.csdn.net/hyl0406445/article/details/53034686
                         mWebView.loadUrl(js);
                        //字体颜色（测试无效，网页加载不出来）
                       // mWebView.loadUrl("javascript:document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#44608a'");
                        //页面背景色
                       // mWebView.loadUrl("javascript:document.getElementsByTagName('body')[0].style.background='#09162E'");
                    }

                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    LoadingDataUtilBlack.dismiss();
                    if(mOnWebViewListener != null){
                        mOnWebViewListener.onwebViewFinish();
                    }
                }

                @Override
                public void onPageCommitVisible(WebView view, String url) {
                    super.onPageCommitVisible(view, url);
                    LoadingDataUtilBlack.dismiss();
                }
            });
            mWebView.loadUrl(url);
        }
    }

    public class ViewHolder extends IViewHolder {
        public ImageView userImg;
        public TextView userName;
        public ImageView likeImg;
        public TextView favourCount;
        public TextView text;
        public TextView replyNum;
        public TextView createTime;
        public ImageView ivNewsCommentIconIntegral;
        public TextView tvNewsCommentIntegral;
        private ViewHolder(View itemView) {
            super(itemView);
            userName = (TextView) itemView.findViewById(R.id.tv_name);
            userImg = (ImageView) itemView.findViewById(R.id.iv_avatar);
            likeImg = (ImageView) itemView.findViewById(R.id.iv_like);
            favourCount = (TextView) itemView.findViewById(R.id.tv_like_count);
            text = (TextView) itemView.findViewById(R.id.tv_comment_item);
            createTime = (TextView) itemView.findViewById(R.id.tv_comment_time);
            replyNum = (TextView) itemView.findViewById(R.id.tv_reply_num);
            tvNewsCommentIntegral = itemView.findViewById(R.id.tv_news_comment_jifen);
            ivNewsCommentIconIntegral = itemView.findViewById(R.id.iv_news_comment_icon_jifen);
        }
    }

    /**
     * 普通评论
     */
    public class NoViewHolder extends ViewHolder {
        private NoViewHolder(View itemView) {
            super(itemView);
        }
    }

    /**
     * 一个回复的评论
     */
    public class OneViewHolder extends ViewHolder {
        private TextView reply1;
        private TextView rePlyCount;

        private OneViewHolder(View itemView) {
            super(itemView);
            reply1 = (TextView) itemView.findViewById(R.id.tv_reply1);
            rePlyCount = (TextView) itemView.findViewById(R.id.tv_reply_count);
        }
    }

    /**
     * 两个回复的评论
     */
    public class TwoViewHolder extends ViewHolder {
        private TextView reply1;
        private TextView reply2;
        private TextView rePlyCount;

        private TwoViewHolder(View itemView) {
            super(itemView);
            reply1 = (TextView) itemView.findViewById(R.id.tv_reply1);
            reply2 = (TextView) itemView.findViewById(R.id.tv_reply2);
            rePlyCount = (TextView) itemView.findViewById(R.id.tv_reply_count);
        }
    }

    /**
     * 三个回复的
     */
    public class ThreeViewHolder extends ViewHolder {
        private TextView reply1;
        private TextView reply2;
        private TextView reply3;
        private TextView rePlyCount;

        private ThreeViewHolder(View itemView) {
            super(itemView);
            reply1 = (TextView) itemView.findViewById(R.id.tv_reply1);
            reply2 = (TextView) itemView.findViewById(R.id.tv_reply2);
            reply3 = (TextView) itemView.findViewById(R.id.tv_reply3);
            rePlyCount = (TextView) itemView.findViewById(R.id.tv_reply_count);
        }
    }


    /**
     * 设置点赞监听
     *
     * @param listener
     */
    public void setOnGoodClickListener(OnGoodClickListener listener) {
        this.mOnGoodClickListener = listener;

    }

    /**
     * 设置取消赞监听
     *
     * @param listener
     */
    public void setOnBadClickListener(OnBadClickListener listener) {
        this.mOnBadClickListener = listener;
    }

    /**
     * 设置Item点击监听
     *
     * @param listener
     */
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public void setOnWebViewListener(OnWebViewListener listener){
        this.mOnWebViewListener = listener;
    }

    public interface OnGoodClickListener<T> {
        void onGoodClick( int position);
    }

    public interface OnBadClickListener<T> {
        void onBadClick( int position);
    }

    public interface OnItemClickListener<T> {
        void onItemClick(View v, int position);
    }

    public interface OnWebViewListener<T> {
        void onwebViewFinish();
    }

    private String js="javascript:window.onload=function() {  \n" +
            "    \n" +
            "    css = document.createElement('link');  \n" +
            "    css.id = 'xxx_browser_2014';  \n" +
            "    css.rel = 'stylesheet';  \n" +
            "    css.href = 'data:text/css,html,body,header,div,a,span,table,tr,td,th,tbody,p,form,input,ul,ol,li,dl,dt,dd,section,footer,nav,h1,h2,h3,h4,h5,h6,em,pre{background: #09172C !important;color:#6a82a5!important;border-color:#454530!important;text-shadow:0!important;-webkit-text-fill-color : none!important;}html a,html a *{color:#5a8498!important;text-decoration:underline!important;}html a:visited,html a:visited *,html a:active,html a:active *{color:#505f64!important;}html a:hover,html a:hover *{color:#cef!important;}html input,html select,html button,html textarea{background:#4d4c40!important;border:1px solid #5c5a46!important;border-top-color:#494533!important;border-bottom-color:#494533!important;}html input[type=button],html input[type=submit],html input[type=reset],html input[type=image],html button{border-top-color:#494533!important;border-bottom-color:#494533!important;}html input:focus,html select:focus,html option:focus,html button:focus,html textarea:focus{background:#5c5b3e!important;color:#fff!important;border-color:#494100 #635d00 #474531!important;outline:1px solid #041d29!important;}html input[type=button]:focus,html input[type=submit]:focus,html input[type=reset]:focus,html input[type=image]:focus,html button:focus{border-color:#494533 #635d00 #474100!important;}html input[type=radio]{background:none!important;border-color:#09172C!important;border-width:0!important;}html img[src],html input[type=image]{opacity:.5;}html img[src]:hover,html input[type=image]:hover{opacity:1;}html,html body {scrollbar-base-color: #4d4c40 !important;scrollbar-face-color: #5a5b3c !important;scrollbar-shadow-color: #5a5b3c !important;scrollbar-highlight-color: #5c5b3c !important;scrollbar-dlight-color: #5c5b3c !important;scrollbar-darkshadow-color: #474531 !important;scrollbar-track-color: #4d4c40 !important;scrollbar-arrow-color: #000 !important;scrollbar-3dlight-color: #6a6957 !important;}dt a{background-color: #09172C !important;}';  \n" +
            "    document.getElementsByTagName('head')[0].appendChild(css);  \n" +
            "    \n" +
            "};  \n";



}
